<?php

namespace Modules\Chinadmin\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Modules\Chinadmin\Models\AccountModel;
use Modules\Chinadmin\Services\CommonServices;
use Modules\System\Services\Mds\MDSCommon;

class User extends Controller
{

    /**
     * Display a listing of the resource.
     * @return Renderable
     * http://l.com/chinadmin/admin/user/login
     */
    public function login(Request $request){

        $i = $request->input();

        $admin = AccountModel::where("username",$i['username'])->first();
        if(empty($admin)){
            $admin = AccountModel::where("phone",$i['username'])->first();
        }

        if(empty($admin)){
            mdsResponse(400,"没有此用户");
        }

//        $ps = Hash::make(123456);
//        var_dump($ps);
//        exit;

        if(!Hash::check($i['password'],$admin['password'])){
            mdsResponse(400,"密码不正确!!!");
        }

        Auth::guard('admin')->login($admin,true);

        AccountModel::where("id",$admin['id'])->update([
            "last_ip" => MDSCommon::get_true_ip(),
            "last_login_time" => date("Y-m-d H:i:s"),
            "login_num" => $admin['login_num']+1,
        ]);

        //如果下面有任何输出并且exit;截断，session就会失效。
        mdsResponse(200,"登录成功","","",0);

    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     * http://l.com/chinadmin/admin/user/logout
     */
    public function logout(){

        Auth::guard('admin')->logout();
        Auth::logout();

        //如果下面有任何输出并且exit;截断
        mdsResponse(200,"退出成功","","",0);

    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     * http://l.com/chinadmin/admin/user/changePassword
     */
    public function changePassword(Request $request){

        $i = $request->input();
        $data['user'] = Auth::guard('admin')->user();

        if($request->ajax()){

            if(!Hash::check($i['oldPassword'],$data['user']['password'])){
                mdsResponse(400,"原密码不正确");
            }

            if(empty($i['name'])){
                mdsResponse(400,"昵称不能为空");
            }

            if($i['password'] != $i['rePassword']){
                mdsResponse(400,"两次密码不一样");
            }

            $up['password'] = Hash::make($i['password']);
            $up['name'] = $i['name'];

            $re = AccountModel::where("id",$data['user']['id'])->update($up);

            mds_if_response($re);

        }

        return view('chinadmin::admin/User/changePassword',$data);

    }


}
